import React, { useRef } from 'react';
import { Button, Dropdown, Table } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { EllipsisOutlined } from '@ant-design/icons';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { config, configT, menu, addPopConfig } from './config';
import AddPaper from '@/components/Collections';
import { delPaper, getPaperList } from '@/services/paper';
import authConfig from '@/config/auth';

export default (prop: any) => {
  const ref = useRef<ActionType>();
  const [proTableConfig, setProTableConfig] = React.useState<configT>();
  const [query, setQuery] = React.useState(prop.history.location.state);

  const updateList = () => {
    if ('current' in ref) ref.current!.reloadAndRest!();
  };

  React.useEffect(() => {
    (async () => {
      setProTableConfig(await config(query));
    })();
  }, []);

  return (
    <PageContainer {...authConfig.PageContainer}>
      <ProTable<request.PaperType>
        columns={proTableConfig?.columns(updateList)}
        request={(params) => {
          // 表单搜索项会从 params 传入，传递给后端接口。
          const res = getPaperList(query || params);
          setQuery(undefined);
          return res;
        }}
        rowSelection={{
          // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
          // 注释该行则默认不显示下拉选项
          selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
        }}
        tableAlertOptionRender={({ selectedRowKeys }) => (
          <Button key="danger" danger onClick={() => {
            delPaper({
              id: selectedRowKeys.join(',')
            })
            updateList()
          }}>
            删除选中试卷
          </Button>
        )
        }
        rowKey="id"
        actionRef={ref}
        pagination={{
          showQuickJumper: true,
        }}
        search={{
          layout: 'vertical',
          defaultCollapsed: false,
        }}
        dateFormatter="string"
        toolbar={{
          title: '试卷列表',
          tooltip: '查看目前已创建的学科',
        }}
        toolBarRender={() => [
          <Button key="show">查看日志</Button>,
          <AddPaper config={addPopConfig} updateList={updateList} />,
          <Dropdown key="menu" overlay={menu}>
            <Button>
              <EllipsisOutlined />
            </Button>
          </Dropdown>,
        ]}
      />
    </PageContainer>
  );
};
